from django.shortcuts import render
# 引入项目的settings文件
from django.conf import settings
# 引入数据库连接的类
from utils.dbconnect import MysqlConn
# Json格式 
from django.http import JsonResponse


# Create your views here.


def index(request):
    """返回首页的页面--显示所有/筛选 """

    # 获取数据库的连接信息
    conn_info = settings.DATABASES['mysql']
    # 实例化一个对象
    obj_mysql_conn = MysqlConn(conn_info)

    # 准备SQL语句
    sql = "Select SNo,SName,Gender,Birthday, Mobile,Email,Address from Student "
    # 先定义一个input_str
    # # 判断是否是POST请求 
    # if request.method == "POST":
    #     # 获取传递的查询条件 
    #     input_str = request.POST.get('txtquery')
    #     # 修改SQL语句
    #     sql += """where 
    #         SNo like '%s' or SName like '%s' or Gender Like '%s' or Mobile Like '%s' or 
    #         Email like '%s' or Address Like '%s'  
    #     """ % ('%' + input_str + '%', '%' + input_str + '%', '%' + input_str + '%', '%' + input_str + '%',
    #            '%' + input_str + '%', '%' + input_str + '%')
    # 取出数据
    obj_mysql_conn.get_db_data(sql)
    # 判断是否成功
    if obj_mysql_conn.flag:
        # 加载页面
        return render(request, 'index.html', {'students': obj_mysql_conn.result})
    else:
        # 返回错误的页面
        return render(request, 'error.html', {'msg': obj_mysql_conn.msg})



def get_students(request):
    """获取查询的数据！--> JSON"""
    # 获取数据库的连接信息
    conn_info = settings.DATABASES['mysql']
    # 实例化一个对象
    obj_mysql_conn = MysqlConn(conn_info)
    # 获取传递过来的条件
    input_str = request.POST.get('input_str')
    # 准备SQL语句

    # 修改SQL语句
    sql = """Select SNo,SName,Gender,Birthday, Mobile,Email,Address from Student where 
            SNo like '%s' or SName like '%s' or Gender Like '%s' or Mobile Like '%s' or 
            Email like '%s' or Address Like '%s'  
        """ % ('%' + input_str + '%', '%' + input_str + '%', '%' + input_str + '%', '%' + input_str + '%',
               '%' + input_str + '%', '%' + input_str + '%')
    # 取出数据
    obj_mysql_conn.get_db_data(sql)
    # 获取数据---[(),(),(),(),]-->[{}，{}，{}，]
    # infos = ['sno', 'sname', 'gender', 'birthday', 'mobile', 'email', 'address']
    # students = []
    # 遍历集合 
    return JsonResponse({'students': obj_mysql_conn.result})
    